package com.example.dubboserver.service.impl;

import com.example.dubboapi.entity.Order;
import com.example.dubboapi.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 订单服务实现类
 * 
 * 演示Dubbo的高级特性：
 * - 集群容错：配置重试和超时
 * - 负载均衡：配置负载均衡策略
 * - 异步调用：可通过配置实现异步
 * - 参数验证：可在实现类中添加验证逻辑
 */
@DubboService(
    interfaceClass = OrderService.class,
    version = "1.0.0",
    timeout = 3000,
    retries = 1,
    loadbalance = "leastactive"  // 最少活跃调用数负载均衡
)
@Slf4j
public class OrderServiceImpl implements OrderService {

    // 模拟数据库存储
    private final ConcurrentHashMap<Long, Order> orderMap = new ConcurrentHashMap<>();
    private final AtomicLong idGenerator = new AtomicLong(1);

    @Override
    public Order createOrder(Order order) {
        log.info("创建订单：{}", order);
        
        // 参数验证
        if (order.getUserId() == null) {
            throw new IllegalArgumentException("用户ID不能为空");
        }
        if (order.getAmount() == null || order.getAmount().compareTo(BigDecimal.ZERO) <= 0) {
            throw new IllegalArgumentException("订单金额必须大于0");
        }
        
        // 设置订单ID和状态
        Long id = idGenerator.getAndIncrement();
        order.setId(id);
        order.setStatus(1); // 1-待支付
        order.setOrderNo(generateOrderNo());
        
        orderMap.put(id, order);
        log.info("订单创建成功，订单ID：{}，订单编号：{}", id, order.getOrderNo());
        
        return order;
    }

    @Override
    public Order getOrderById(Long id) {
        log.info("根据ID查询订单：{}", id);
        Order order = orderMap.get(id);
        if (order == null) {
            log.warn("订单不存在：{}", id);
        }
        return order;
    }

    @Override
    public Order getOrderByOrderNo(String orderNo) {
        log.info("根据订单编号查询订单：{}", orderNo);
        return orderMap.values().stream()
                .filter(order -> order.getOrderNo().equals(orderNo))
                .findFirst()
                .orElse(null);
    }

    @Override
    public List<Order> getOrdersByUserId(Long userId) {
        log.info("根据用户ID查询订单列表：{}", userId);
        return orderMap.values().stream()
                .filter(order -> order.getUserId().equals(userId))
                .toList();
    }

    @Override
    public Order updateOrderStatus(Long id, Integer status) {
        log.info("更新订单状态，订单ID：{}，状态：{}", id, status);
        
        Order order = orderMap.get(id);
        if (order == null) {
            log.warn("订单不存在：{}", id);
            return null;
        }
        
        // 状态验证
        if (status < 1 || status > 5) {
            throw new IllegalArgumentException("订单状态值无效");
        }
        
        order.setStatus(status);
        log.info("订单状态更新成功：{}", order);
        
        return order;
    }

    @Override
    public boolean cancelOrder(Long id) {
        log.info("取消订单：{}", id);
        
        Order order = orderMap.get(id);
        if (order == null) {
            log.warn("订单不存在：{}", id);
            return false;
        }
        
        // 只有待支付状态的订单才能取消
        if (order.getStatus() != 1) {
            log.warn("订单状态不是待支付，无法取消：{}", id);
            return false;
        }
        
        order.setStatus(5); // 5-已取消
        log.info("订单取消成功：{}", id);
        
        return true;
    }

    /**
     * 生成订单编号
     */
    private String generateOrderNo() {
        return "ORD" + System.currentTimeMillis() + String.format("%04d", (int)(Math.random() * 10000));
    }
}